<template>
	<view class="merge-img" v-else-if="type === 'mergeImg'">
		<view class="express-detail-company">
			<view class="title">图片拼接</view>
			<view class="intor">将已选择的图片拼接成长图，一次最多可添加9张，拼接数量不限数量，点击保存图片按钮可将图片保存到本地设备。</view>
		</view>
		<view style="background-color: #fff;margin-top:20rpx;">
			<view style="color:#d81e06;padding:20rpx;font-size:26rpx;font-weight:600;">温馨提示：点击保存图片按钮可将图片保存到本地设备。</view>
			<view class="merge-img-btn">
				<u-button style="margin: 0 30rpx;" @click="choseImg" size="mini" type="primary">选择图片</u-button>
				<u-button style="margin: 0 30rpx;" @click="previewImg" size="mini" type="primary">图片预览</u-button>
				<u-button style="margin: 0 30rpx;" @click="previewImageClick" size="mini" type="success">保存图片</u-button>
				<u-button v-if="imgResult.length" style="margin: 0 30rpx;" @click="clearFn" size="mini">清空图片</u-button>
			</view>
			<canvas v-if="clearFlag" :style="'width:'+width+'px;height:'+height+'px'" canvas-id="mergeImgCanvas"></canvas>
		</view>
	</view>
</template>

<script>
	let ctx;
	export default {
		name:"mergeImages",
		props:{
			maxCount: {
				type: Number,
				default: 1
			}
		},
		watch: {
			maxCount:{
				handler(newVal,oldVal){
					this.curMaxCount = newVal;
				},
				immediate:true
			}
		},
		data() {
			return {
				width:0,
				height:0,
				imgUrl:'',
				imgResult: [],
				prevHeight: 0,
				clearFlag: true,
				curMaxCount: 0
			}
		},
		methods: {
			// 选择图片并把图绘制到canvas里
			choseImg(){
				// 获取屏幕宽度与高度
				const screenWidth = uni.getSystemInfoSync().screenWidth;
				let ratio = 0;
				const _this = this;
				let curImageIndex = 0;
				uni.chooseImage({
				  count:_this.curMaxCount,
				  sizeType: ['original', 'compressed'],
				  sourceType: ['album', 'camera'],
				  success(res){
					  uni.showLoading({
					  	icon:'none',
					  	title: '图片绘制中...',
					  	mask: true
					  })
					  if(res.tempFilePaths && res.tempFilePaths.length){
						  const dpr = wx.getSystemInfoSync().pixelRatio
						  // 图片绘制
						  const drawImageFn = ()=>{
							  // 当前图片
							  const curImgUrl = res.tempFilePaths[curImageIndex];
							  // 获取图片宽高
							  uni.getImageInfo({
							  	src: curImgUrl,
							  	success (imgRes) {
								  // console.log(imgRes)
								  // 绘画图片
								  // 屏幕宽度与图片实际宽比例
								  ratio = screenWidth/imgRes.width;
								  _this.width = parseInt(ratio*imgRes.width);
								  // 给canvas的高度
								  _this.height += parseInt(ratio*imgRes.height);
								  ctx.drawImage(curImgUrl, 0, _this.imgResult.length ? _this.prevHeight : 0, ratio*imgRes.width, ratio*imgRes.height);
								  // 记录上一张图片的高度
								  _this.prevHeight += parseInt(ratio*imgRes.height);
								  ctx.draw(true,()=>{
									uni.hideLoading();
									curImageIndex+=1;
									if(curImageIndex < res.tempFilePaths.length){
										drawImageFn();
									}
								  })
								  // 用于区分是否添加了第一张图片 drawImage第三个参数做判断第一张图片值为0，其他取累计高度值
								  _this.imgResult.push(curImgUrl);
							  	}
							  });
						  }
						  // 开始绘图
						  drawImageFn();
					  }
				  }
				})
			},
			// 点击图片预览第一次先观看广告
			previewImageClick(){
				if(this.imgResult.length < 2){
					return uni.showToast({
						icon:'none',
						title: '请先选择2张图片'
					});
				}
				this.saveImg();
			},
			// 图片预览
			previewImg(){
				if(this.imgResult.length < 2){
					return uni.showToast({
						icon:'none',
						title: '请先选择2张图片'
					});
				}
				const _this = this;
				uni.showLoading({
					icon:'none',
					title: '图片拼接中...',
					mask: true
				})
				uni.canvasToTempFilePath({
				   canvasId: 'mergeImgCanvas',
				   success(saveRes) {
					 // console.log('拼接后的图片临时路径：', saveRes.tempFilePath);
					 if(saveRes && saveRes.tempFilePath){
						 uni.hideLoading();
						 // 图片预览
						 uni.previewImage({
						 	urls:[saveRes.tempFilePath]
						 });
						 _this.$emit('getImgUrl',saveRes.tempFilePath);
					 }
				   },
				   fail(err) {
					 // console.error(err);
					 uni.hideLoading();
				   }
				},this);
			},
			// 图片保存
			saveImg(){
				const _this = this;
				uni.showLoading({
					icon:'none',
					title: '图片保存中...',
					mask: true
				})
				uni.canvasToTempFilePath({
				   canvasId: 'mergeImgCanvas',
				   success(saveRes) {
					 // console.log('拼接后的图片临时路径：', saveRes.tempFilePath);
					 if(saveRes && saveRes.tempFilePath){
						 uni.hideLoading();
						 // 图片保存
						 uni.saveImageToPhotosAlbum({
						 	filePath: saveRes.tempFilePath,
						 	success() {
						 		uni.showToast({
						 			icon:'none',
						 			title:'图片保存成功'
						 		})
						 	},
						 	fail(err) {
						 		console.log(err)
						 	}
						 })
						 _this.$emit('getImgUrl',saveRes.tempFilePath);
					 }
				   },
				   fail(err) {
					 // console.error(err);
					 uni.hideLoading();
				   }
				},this);
			},
			// 清空canvas
			clearFn(){
				this.clearFlag = false;
				this.prevHeight = 0;
				this.imgResult = [];
				this.height = 0;
				uni.showLoading({
					icon:'none',
					title: '图片清除中...',
					mask: true
				})
				setTimeout(()=>{
					this.clearFlag = true;
					uni.hideLoading();
				},300);
			}
		},
		created(){
			// 组件内需要第二个值需要传this不然canvas不显示
			ctx = wx.createCanvasContext('mergeImgCanvas', this);
		}
	}
</script>

<style lang="less">
</style>